<template>
    <div>
        <button @click="makeOrder">下单</button>
        <br>
        <img :src="imgUrl">
    </div>
</template>

<script>
    export default {
        name: "PayView.vue",
        data(){
            return {
                codeUrl: '' ,   //二维码url路径
                imgUrl: '',     //图片路径
                tradeNo: '',    //订单号
                count: 0,        //检查次数
                interval: null
            }
        },
        methods:{
            makeOrder(){
                //微信下单
                this.$http.post("/makeOrder?userId=1&productId=999&price=1")
                    .then(resp => {
                        //获得微信支付相关数据
                        if(resp.data){
                            this.codeUrl = resp.data.code_url;
                            this.tradeNo = resp.data.trade_no;
                            //访问二维码接口生成支付二维码
                            this.imgUrl = 'http://localhost:8080/code?url=' + this.codeUrl;
                            //轮询检查订单的支付状态
                            var _this = this
                            //启动定时器
                            this.internal = setInterval(() => {
                                _this.count++;
                                _this.$http.post("/checkOrder?tradeNo=" + _this.tradeNo).then(
                                    resp => {
                                        console.log('检查结果' + resp.data)
                                        if(resp.data == 'SUCCESS'){
                                            alert('支付成功')
                                            _this.imgUrl = ''
                                            //停止轮询
                                            clearInterval(_this.internal)
                                        }else if(_this.count == 10){
                                            alert('支付超时')
                                            _this.imgUrl = ''
                                            //停止轮询
                                            clearInterval(_this.internal)
                                        }
                                    }
                                );
                            },6000);
                        }
                    })
            },
        }
    }
</script>

<style scoped>

</style>